import * as actionTypes from "./constants";

import { getSongDetails } from "@/services/player";

import { getLyric } from "@/services/song";

const getSongDetailsAction = (res) => ({
  type: actionTypes.PLAYDETAILACTION,
  songDetails: res.songs,
});

const getSongDetailsAllAction = (res) => ({
  type: actionTypes.PLAYDETAILACTIONALL,
  songDetailsAll: res.songs,
});

const getLyricAction = (res) => ({
  type: actionTypes.LYRIC,
  lyric: res,
});
// 增加songid
const addSongIdAction = (id) => ({
  type: actionTypes.ADDSONGID,
  addSongId: id,
});
//获取songid
const getSongIdsAction = (ids) => ({
  type: actionTypes.SONGIDS,
  songIds: ids,
});
//删除全部songid
const deleteSongIdsAction = (ids) => ({
  type: actionTypes.DELETESONGIDALL,
  deleteIds: ids,
});
//删除一个songid
const deleteSongIdAction = (ids) => ({
  type: actionTypes.DELETESONGID,
  deleteId: ids,
});
export const getSongDetailsMessage = (ids) => {
  return (dispatch) => {
    getSongDetails(ids).then((res) => {
      dispatch(getSongDetailsAction(res));
    });
  };
};

export const getSongDetailsAll = (ids) => {
  return (dispatch) => {
    getSongDetails(ids).then((res) => {
      dispatch(getSongDetailsAllAction(res));
    });
  };
};

export const getLyricList = (id) => {
  return (dispatch) => {
    getLyric(id).then((res) => {
      dispatch(getLyricAction(res));
    });
  };
};
// 获取songid
export const getSongIds = (ids) => {
  return (dispatch) => {
    dispatch(getSongIdsAction(ids));
  };
};
// 增加songid
export const addSongId = (id) => {
  return (dispatch) => {
    // 当ids存在时
    // (JSON.parse(window.localStorage.getItem("ids")).indexOf(id))
    if (JSON.parse(window.localStorage.getItem("ids")) != null) {
      // 当传进来的id在ids不存在时
      if (JSON.parse(window.localStorage.getItem("ids")).indexOf(id) === -1) {
        const arrId = JSON.parse(window.localStorage.getItem("ids"));
        arrId.push(id);
        window.localStorage.setItem("ids", JSON.stringify(arrId));
        dispatch(addSongIdAction(arrId));
      } else {
        return;
      }
    } else {
      let arr = [];
      arr.push(id);
      window.localStorage.setItem("ids", JSON.stringify(arr));
      dispatch(addSongIdAction(arr));
    }
  };
};
// 删除全部id
export const deleteSongAllIds = () => {
  return (dispatch) => {
    if (JSON.parse(window.localStorage.getItem("ids")) != null) {
      window.localStorage.removeItem("ids");
      dispatch(deleteSongIdsAction([]));
    } else {
      return;
    }
  };
};

// 删除一个id

export const deleteSongId = (id) => {
  return (dispatch) => {
    if (JSON.parse(window.localStorage.getItem("ids")).length === 0) {
    }
    if (JSON.parse(window.localStorage.getItem("ids")) != null) {
      const arrId = JSON.parse(window.localStorage.getItem("ids"));
      const newArrIds = arrId.filter((item) => item !== id);
      window.localStorage.setItem("ids", JSON.stringify(newArrIds));
      dispatch(deleteSongIdAction(newArrIds));
    } else {
      return;
    }
  };
};
